package com.github.tifezh.kchartlib.chart.formatter;

import android.text.TextUtils;

import com.github.tifezh.kchartlib.chart.base.IValueFormatter;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;

/**
 * Value格式化类
 * Created by tifezh on 2016/6/21.
 */

public class ValueFormatter implements IValueFormatter {
    @Override
    public String format(float value) {
        return keep(value + "", 8, true);
    }

    /**
     * 保留几位小数
     *
     * @param number  原数据
     * @param keepNum 小数位数
     * @param isMax   是否最多保留几位
     * @return 处理后数据
     */
    public static String keep(String number, int keepNum, boolean isMax) {
        if (TextUtils.isEmpty(number)) {
            return 0 + "";
        }
        try {
            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(keepNum);
            if (!isMax) {
                nf.setMinimumFractionDigits(keepNum);
            }
            nf.setGroupingUsed(false);
            // 如果不需要四舍五入，可以使用RoundingMode.DOWN
            nf.setRoundingMode(RoundingMode.HALF_UP);
            return nf.format(new BigDecimal(number).doubleValue());
        } catch (Exception e) {
            return "0";
        }

    }


}
